package com.iwhalecloud.bss.kite.cucc.web.controller.batch;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.batch.IBatchAcceptAdjustmentService;
import com.iwhalecloud.bss.kite.cucc.client.api.batch.IBatchAcceptService;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetail;
import com.iwhalecloud.bss.kite.cucc.client.vo.batch.BatchAccepImportFileVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.BusimportDetailVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccOfferInitVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalErrorConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.web.controller.scene.SceneInitController;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteAttrDTO;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.base.annotation.IgnoreSession;
import com.ztesoft.bss.common.util.SpringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @author lyx
 * @version V1.0
 * @Description:
 * @date 2021/6/1
 * @Package com.iwhalecloud.bss.kite.cucc.web.controller.batch
 */
@RestController
@RequestMapping("/batchAccept")
@Api(tags = {"/batchAccept - 极简批量受理"
})
public class LocalBatchAcceptController {

    @Autowired
    private IBatchAcceptService batchAcceptService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Resource
    private IBatchAcceptAdjustmentService batchAcceptAdjustmentService;

    @ApiOperation(value = "批量受理场景初始化", notes = "批量受理场景初始化，返回场景实例标识")
    @PostMapping("/init")
    public DataResult<String> initBatchAcceptScene(@RequestBody CuccOfferInitVO offerVO) {
        offerVO.setIsBatchAccept(Boolean.TRUE);
        String sceneInstId = SpringUtil.getBean(SceneInitController.class).initOfferScene(offerVO).getResultObject();
        return ErrorConsts.SUCCESS.getResult(sceneInstId);
    }

    @ApiOperation(value = "是否允许批量受理", notes = "判断是否允许批量受理")
    @PostMapping("/isBatchAcceptGoods")
    public DataResult<Boolean> isBatchAcceptGoods(@RequestBody CuccOfferInitVO offerVO) {
        Offer offer = OfferCache.get(offerVO.getOfferId());
        BatchAcceptUtil.isBatchAcceptGoods(offer);
        // mv特殊判断：PE网络只能选省内
        if (KiteStringUtils.equals(offer.getAttrValue("cateId"), "2004017")) {
            AtomicBoolean isProvince = new AtomicBoolean(false);
            offerVO.getSingleOffers().forEach(singleOffer -> {
                if (KiteListUtils.isEmpty(singleOffer.getAttrs())) {
                    return;
                }
                String pe = singleOffer.getAttrs().stream().filter(attr -> KiteStringUtils.equals(attr.getFieldName(), "2_0000048"))
                    .findFirst().map(KiteAttrDTO::getValue).orElse(null);
                if (KiteStringUtils.equals(pe, "1_0000223")) {
                    isProvince.set(true);
                }
            });
            if (!isProvince.get()) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("此商品不允许批量受理，如需要，请联系管理员修改配置");
            }
        }

        return ErrorConsts.SUCCESS.getResult(Boolean.TRUE);
    }

    @KiteTransactional
    @ApiOperation(value = "删除单条导入数据", notes = "删除单条导入数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "batchId", value = "批次号"),
        @ApiImplicitParam(name = "detailId", value = "明细ID")
    })
    @PostMapping("/deleteDetailData")
    public DataResult<Boolean> deleteDetailData(@RequestParam String batchId, @RequestParam String detailId) {
        String custId = KiteWebContext.getContext().getCustId();
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();

        //        String offerInstId = batchAcceptService.deleteDetailData(sceneInstId, custId, batchId, detailId);
        //        return ErrorConsts.SUCCESS.getResult(batchAcceptService.deleteOfferInstAndRelInsts(sceneInstId, custId, offerInstId));
        return ErrorConsts.SUCCESS.getResult(batchAcceptAdjustmentService.deleteRecord(batchId, sceneInstId, custId, detailId));
    }

    @KiteTransactional
    @ApiOperation(value = "批量受理录入导入", notes = "批量受理录入导入")
    @PostMapping(produces = "application/json;charset=utf-8", value = "/importBatchAcceptData")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "file", value = "file", required = true, dataType = "file", paramType = "form"),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例id")
    })
    public DataResult<String> importBatchAcceptData(@RequestParam(value = "file") MultipartFile file,
        String sceneInstId) throws Exception {

        String fileName = file.getOriginalFilename();
        String fileType = KiteStringUtils.substring(fileName, fileName.lastIndexOf('.') + 1);
        if (!KiteStringUtils.equalsAny(fileType, "xls", "xlsx")) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("只允许上传excel格式文件");
        }
        boolean isXls = "xls".equals(fileName.substring(fileName.lastIndexOf('.') + 1));
        String importType = LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_4000;
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        if (Objects.nonNull(sceneInst) && KiteStringUtils
            .equals(LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN, sceneInst.getServiceOfferId())) {
            importType = LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_6100;
        }
        else if (Objects.nonNull(sceneInst) && KiteStringUtils
            .equals(LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT, sceneInst.getServiceOfferId())) {
            importType = LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_6200;
        }
        String result = batchAcceptService
            .importBatchAcceptData(file.getInputStream(), isXls, sceneInstId, fileName, importType, null);
        return ErrorConsts.SUCCESS.getResult(result);
    }

    @KiteTransactional
    @ApiOperation(value = "批量受理-调整记录-修正/覆盖", notes = "批量受理-调整记录-修正/覆盖")
    @PostMapping(produces = "application/json;charset=utf-8", value = "/updateBatchAcceptData")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "file", value = "file", required = true, dataType = "file", paramType = "form"),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例id"),
        @ApiImplicitParam(name = "adjustType", value = "操作类型：1修正，2覆盖")
    })
    public DataResult<String> updateBatchAcceptData(@RequestParam(value = "file") MultipartFile file,
        @RequestParam String sceneInstId, @RequestParam String adjustType) throws Exception {

        String fileName = file.getOriginalFilename();
        String fileType = KiteStringUtils.substring(fileName, fileName.lastIndexOf('.') + 1);
        if (!KiteStringUtils.equalsAny(fileType, "xls", "xlsx")) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut(LocalErrorConsts.BSS_KITE_BATCH_50004.getMsg());
        }
        boolean isXls = "xls".equals(fileName.substring(fileName.lastIndexOf('.') + 1));

        String result = "";
        //if (KiteStringUtils.equals(adjustType, LocalKeyConsts.KITE_BATCH_ADJUST_TYPE_1)) {
        //    result = batchAcceptService.updateBatchAcceptData(file.getInputStream(), isXls, sceneInstId, fileName,
        //        LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_4000);
        //}
        if (KiteStringUtils.equals(adjustType, LocalKeyConsts.KITE_BATCH_ADJUST_TYPE_1)) {
            result = batchAcceptService.converBatchAcceptData(file.getInputStream(), isXls, sceneInstId, fileName,
                LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_4000);
        }
        else {
            result = LocalErrorConsts.BSS_KITE_BATCH_50003.getMsg();
        }

        return ErrorConsts.SUCCESS.getResult(result);
    }

    @ApiOperation(value = "批量受理录入-文件导入列表查询", notes = "批量受理录入-文件导入列表查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "offerInstId", value = "销售品实例Id"),
        @ApiImplicitParam(name = "custId", value = "客户Id"), @ApiImplicitParam(name = "sceneInstId", value = "场景实例Id")
    })
    @GetMapping("/listImportFile")
    public DataResult<List<BatchAccepImportFileVO>> listImportFile(String offerInstId, String custId,
        String sceneInstId) {
        return ErrorConsts.SUCCESS.getResult(batchAcceptService.listImportFile(sceneInstId, offerInstId, custId));
    }

    @ApiOperation(value = "批量受理录入-文件导入详情列表查询", notes = "批量受理录入-文件导入详情列表查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "custId", value = "客户Id"),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例Id"),
        @ApiImplicitParam(name = "searchContent", value = "搜索内容"), @ApiImplicitParam(name = "pageNum", value = "页数"),
        @ApiImplicitParam(name = "pageSize", value = "分页大小")
    })
    @GetMapping("/listImportDetails")
    public DataResult<PageInfo<BusimportDetailVO>> listImportDetails(@RequestParam(required = true) String custId,
        @RequestParam(required = true) String sceneInstId, String searchContent,
        @RequestParam(required = true) Integer pageNum, @RequestParam(required = true) Integer pageSize) {
        return ErrorConsts.SUCCESS
            .getResult(batchAcceptService.listImportDetails(custId, sceneInstId, searchContent, pageNum, pageSize));
    }

    @KiteTransactional
    @ApiOperation(value = "批量受理录入-文件导入删除", notes = "批量受理录入-文件导入删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "fileType", value = "文件类型"),
        @ApiImplicitParam(name = "offerInstId", value = "销售品实例Id"), @ApiImplicitParam(name = "custId", value = "客户Id"),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例Id")
    })
    @DeleteMapping("/deleteImportFile")
    public DataResult<Boolean> deleteImportFile(String fileType, String offerInstId, String custId,
        String sceneInstId) {
        batchAcceptService.deleteImportFile(sceneInstId, fileType, custId, offerInstId);
        return ErrorConsts.SUCCESS.getResult(Boolean.TRUE);
    }

    @ApiOperation(value = "批量受理录入-数据合规性校验", notes = "批量受理录入-数据合规性校验")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例Id"),
        @ApiImplicitParam(name = "batchId", value = "批次号")
    })
    @GetMapping("/checkData")
    public DataResult<Boolean> checkData(String sceneInstId, String batchId) {
        if (KiteStringUtils.isEmpty(batchId)) {
            batchId = this.querySceneInstService.getExtParameterValue(sceneInstId, "batchId");
        }
        batchAcceptService.checkData(sceneInstId, batchId);
        return ErrorConsts.SUCCESS.getResult(Boolean.TRUE);
    }

    @ApiOperation(value = "调整页面返回上一步", notes = "调整页面返回上一步")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例Id")
    })
    @PostMapping("/back2UploadPage")
    @KiteTransactional
    public DataResult<Boolean> back2UploadPage(String sceneInstId) {
        return ErrorConsts.SUCCESS.getResult(batchAcceptAdjustmentService.back2UploadPage(sceneInstId));
    }

    @ApiOperation(value = "单个修改-将导入记录实例化", notes = "单个修改-将导入记录实例化")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例Id"),
        @ApiImplicitParam(name = "batchId", value = "批次号ID"),
        @ApiImplicitParam(name = "detailId", value = "记录标识，kiteBatchAcceptDetail记录的主键")
    })
    @PostMapping("/modify/instantiate")
    @KiteTransactional
    public DataResult<String> instantiate(String sceneInstId, String batchId, String detailId) {
        KiteBatchAcceptDetail kiteBatchAcceptDetail = batchAcceptService.getBatchAcceptDetail(detailId, batchId);
        batchAcceptAdjustmentService.instantiate(sceneInstId, kiteBatchAcceptDetail, null, null);
        return ErrorConsts.SUCCESS.getResult("400");
    }

    @ApiOperation(value = "单个修改-保存", notes = "单个修改-保存")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例Id"),
        @ApiImplicitParam(name = "detailId", value = "记录标识，kiteBatchAcceptDetail记录的主键")
    })
    @PostMapping("/modify/save")
    public DataResult<Boolean> saveModification(String sceneInstId, String batchId, String detailId) {
        return ErrorConsts.SUCCESS.getResult(batchAcceptAdjustmentService.saveModification(sceneInstId, batchId, detailId));
    }

    @ApiOperation(value = "单个修改-取消", notes = "单个修改-取消")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例Id")
    })
    @PostMapping("/modify/cancle")
    public DataResult<Boolean> cancelModification(String sceneInstId) {
        String custId = KiteWebContext.getContext().getCustId();
        return ErrorConsts.SUCCESS.getResult(batchAcceptAdjustmentService.cancelModification(sceneInstId, custId));
    }

    @KiteTransactional
    @ApiOperation(value = "重新提交订单", notes = "重新提交订单")
    @ApiImplicitParams({@ApiImplicitParam(name = "batchId", value = "批次标识，kiteBatchAccept的主键")
    })
    @PostMapping("/recommit")
    public DataResult<Boolean> recommit(String batchId) {
        return ErrorConsts.SUCCESS.getResult(batchAcceptAdjustmentService.recommit(batchId));
    }

    @KiteTransactional
    @ApiOperation(value = "提交订单时初始化实例", notes = "提交订单时初始化实例")
    @ApiImplicitParams({ @ApiImplicitParam(name = "sceneInstId", value = "场景实例Id"),
        @ApiImplicitParam(name = "batchId", value = "批次标识，kiteBatchAccept的主键")
    })
    @PostMapping("/commitInstantiate")
    public DataResult<String> commitInstantiate(String sceneInstId, String batchId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        return batchAcceptAdjustmentService.commitInstantiate(sceneInstId, batchId);
    }

    @IgnoreSession
    @ApiOperation(value = "转单定时任务调试", notes = "转单定时任务调试")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例Id")
    })
    @PostMapping("/commitJob")
    public DataResult<String> commitJob(String sceneInstId) {
        batchAcceptAdjustmentService.commitJob();
        return ErrorConsts.SUCCESS.getResult("");
    }
}
